import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
import axios from 'axios'
export default new Vuex.Store({
  // 相当于组件的data
  state: {
    todos: []
  },
  // 相当于 组件的computed
  // 一般在这里做筛选
  getters: {
    list1(state) {
      return state.todos.filter(item => item.isFinish)
    },
    list2(state) {
      return state.todos.filter(item => !item.isFinish)
    }
  },
  // 相当于组件的methods
  // 必须是同步代码
  mutations: {
    DELETE_TODOS(state, id) {
      state.todos = state.todos.filter(item => item.id !== id)
    },
    ADD_TODOS(state, payload) {
      state.todos.push(payload)
    },
    FETCH_TODOS(state, payload) {
      state.todos = payload
    }
  },
  // 相当于组件的methods 
  // 但是这里可以发起异步请求
  actions: {
    FETCH_TODOS(context) {
      axios.get('/todos').then(resp => {
        context.commit('FETCH_TODOS', resp.data)
      })
    }
  },
  modules: {
  }
})
